package com.weiaibenpao.demo.chislim.retrofit;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.net.ConnectivityManager;
import android.text.TextUtils;

import com.orhanobut.logger.Logger;
import com.weiaibenpao.demo.chislim.api.APIService;
import com.weiaibenpao.demo.chislim.utils.Utils;

import java.io.IOException;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by wlx on 2017/12/4.
 */

public class RetrofitUtils {
    /**
     * 服务器地址
     */
    private static String BASE_URL;
    private static Application mContext;

    public static APIService getAPIService() {
//        Object o = apis.get(c);
//        if (o == null) {
//            o = getInstance().create(c);
//            apis.put(c, o);
//        }
        return getInstance().create(APIService.class);
    }

    /**
     * 初始化
     * @param baseUrl
     * @param context
     */
    public static synchronized void  init(String baseUrl,Application context){
        if (TextUtils.isEmpty(baseUrl)){
            return;
        }
        mContext=context;
        BASE_URL=baseUrl;

    }
    public static Retrofit getInstance(){
        HttpLoggingInterceptor interceptor=new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Logger.e("RetrofitUtils:"+message);
            }
        });
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        //设置缓存
        Interceptor cacheInterceptor=new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                //拿到请求体
                Request request = chain.request();
                //读取接口上的@Headers里面的注解配置
                String cacheControl = request.cacheControl().toString();
                //判断没有网络并且添加了@Headers注解,才使用网络缓存.
                if (!Utils.isNetWorkConnected()&&!TextUtils.isEmpty(cacheControl)){
                    request= request.newBuilder().
                            cacheControl(CacheControl.FORCE_CACHE).
                            build();
                }

                //如果没有添加注解，则不缓存
                if (TextUtils.isEmpty(cacheControl) || "no-store".contains(cacheControl)) {
                    //响应头设置成无缓存
                    cacheControl="no-store";
                }else if (Utils.isNetWorkConnected()){
                    //如果有网络，则将缓存的过期时间，设置为0，获取最新数据
                    cacheControl="public,max-age"+0;
                }else {
                    //如果没有网络，则根据@headers注解的设置进行缓存
                }
                Response response = chain.proceed(request);
//                Logger.e("intercept: " + response);

                return response.newBuilder().
                        header("Cache-Control",cacheControl).
                        removeHeader("Pragma").
                        build();
            }
        }  ;
        OkHttpClient.Builder client = new OkHttpClient.Builder().
                        //拦截log
                        addInterceptor(interceptor).
                        //拦截并设置缓存
//                        addNetworkInterceptor(cacheInterceptor).
                        //拦截并设置缓存
                        addInterceptor(cacheInterceptor).
                        cache(new Cache(mContext.getCacheDir(),10240*1024));
//        for (Interceptor i : NetWorkManager.mInterceptors) {
//            client.addInterceptor(i);
//        }

        return new Retrofit.Builder().
                client(client.build()).
                baseUrl(BASE_URL).
                addConverterFactory(GsonConverterFactory.create()).
                addCallAdapterFactory(RxJava2CallAdapterFactory.create()).
                build();
    }
    /**
     * 判断网络是否打开
     *
     * @return
     */
    public static boolean isOpenInternet(Context context) {
        ConnectivityManager con = (ConnectivityManager) context.getSystemService(Activity.CONNECTIVITY_SERVICE);
        boolean wifi = con.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
        boolean internet = con.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();
        return wifi || internet;
    }
}
